package controllers

import (
	"autoPage/models"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
)

type LoginController struct {
	BaseController
}

type Dmsuse struct {
	Id    int    `form:"-"`
	Uname string `form:"uname"`
	Pwd   string `form:"pwd"`
}

func (lg *LoginController) Get() {
	lg.TplName = "login.html"
}

func (lg *LoginController) Post() {
	u := Dmsuse{}
	if err := lg.ParseForm(&u); err != nil {
		logs.Info(err)
	} else {
		res := models.GetUserByNameAndPwd(u.Uname, lg.MD5(u.Pwd))
		if res == nil {
			beego.Error("用户名或密码错误")
			lg.Data["json"] = `[{"data":null,"msg":"用户名或密码错误"}]`
			lg.TplName = "login.html"
		} else {
			lg.Data["json"] = res
			lg.SetSession("uid", res[0].Id)
			lg.SetSession("uname", res[0].Uname)
			lg.SetSession("username", res[0].UserName)
			lg.Ctx.Redirect(302, "pageconfig/list")
		}
	}
}

func (lg *LoginController) Logout() {
	lg.SetSession("uname", "")
	lg.SetSession("uid", -1)
	lg.Ctx.Redirect(302, "/login")
}
